import { initExecute } from './index.js';
const typeTitles = { add: '新增', edit: '编辑' };
export default function(midder) {
	const exec = initExecute.call(this, midder);
	// buttons和hasButtons等，均通过param注入
	return (is, customFn, { type, title, param, ...other } = {}) => {
		const { record = {}, ...attrs } = other;
		return new Promise((resolve, reject) => {
			if (type && !midder[type]) midder[type] = {};
			this.$tan({
				title: title || typeTitles[type],
				children: { is, type, midder, record, ...attrs },
				onOk: async close => {
					// 解构出一些必要参数
					let { action, actions, httpParam } = midder[type];
					// 优先使用action，且具备兼容特性
					if (action) actions = [action];
					// 获取表单数据
					let r = {};
					if (actions) r = await Promise
						.all(actions.map(action => action.value()))
						.then(arr => arr.reduce((curr, total) => {
							return Object.assign(total, curr)
						}, {}));
					// httpParam为预留的合并参数
					r = Object.assign(r, httpParam);
					// 调用用户提供的回调，执行请求操作
					await customFn(r, close);
					midder.table.reload();
					resolve();
					close();
				},
				...param
			})
		})
	}
}